<?php

namespace app\merchants\services;

use app\common\loader\ModelMerchant;
use app\common\loader\ModelShop;
use app\common\loader\ModelVirtual;
use think\db\exception\DbException;
use think\Exception;

/**
 * 商品管理
 */
class ProductService
{
    /**
     * 商品列表
     * @param  $where |搜索条件
     * @param  $page |页码
     * @throws DbException
     */
    public function Propage($where, int $page = 1, $count = 30)
    {
        return ModelMerchant::Product()->proPage($where, $page, $count);
    }


    /**
     * 修改状态
     * @param int $id | 主键
     * @param     $data | 更新插入数据
     * @throws \Exception
     */
    public function save_stock($data, int $id = 0): bool
    {
        return ModelMerchant::Product()->where('id', $id)->where('mer_id', $data['mer_id'])
            ->update(null, $data);
    }


    /**
     * 添加、修改
     * @param int $id | 主键
     * @param     $data | 更新插入数据
     * @throws \Exception
     */
    public function save($data, int $id = 0): bool
    {
        return ModelMerchant::Product()->proSave($data, $id);
    }


    /**
     * 软删除
     * @param int $id | 主键
     * @throws \Exception
     */
    public function del(int $id, $mer_id): void
    {
        $code = ModelMerchant::Product()->where(['id' => $id, 'mer_id' => $mer_id])->value(null, 'code');
        if (ModelVirtual::VirtualPromoProduct()->where(['mer_id' => $mer_id, 'product_code' => $code])->count('id') > 0) {
            throw  new Exception('该商品已参加活动无法删除');
        }

        if (ModelShop::ShopStock()->where(['mer_id' => $mer_id, 'product_code' => $code])->sum('sum_num') > 0) {
            throw  new Exception('该商品下有虚码数量,无法删除,请先回收虚码.');
        }
        $data = ModelMerchant::Product()->where(['id' => $id, 'mer_id' => $mer_id])
            ->update(null, ['delete_at' => date('Y-m-d H:i:s', time())]);
        if (!$data) {
            throw new Exception('删除失败', API_ERROR);
        }

    }

    /**
     * 商品详情
     * @param int $id | 主键
     * @throws \Exception
     */
    public function info(int $id)
    {
        return ModelMerchant::Product()->proInfo($id);

    }

    /**
     * 列表
     * @param $where
     * @param $list_num
     * @return mixed
     */
    public function list($where, $list_num ,$field)
    {
        return ModelMerchant::Product()->list($where, $list_num,$field);
    }
}
